<?
require_once('includes/appInit.php');
include('includes/ajax/sysData.php');
include('includes/ajax/ajaxResources.php');

$statusDivDisplay = 'none';	
$formAction       = 'add';
/*
 * From here....
 */
if ($_POST['upload'] == 1) {
	$error = 0;
	$upload = 1;
	$formAction = $_POST['formAction'];

	$fID         = $_POST['fID'];
	$fileCat     = $_POST['fileCat'];
	$fileSubCat  = $_POST['fileSubCat'];
	$fileTitle   = fieldToDB($_POST['fileTitle']);
	$fileDesc    = $_POST['fileDesc'];
	$newCatField = fieldToDB($_POST['newCatFieldMain']);
	$newSubCatField = fieldToDB($_POST['newCatFieldSub']);
	$ptiSharedResource = $_POST['ptiSharedResource'];
	
	if ( ($fileCat == 'Select...') && empty($newCatField) ) {
		$error = 1;
		$message = 'You must select a category for this file.';
		$statusDivDisplay = '';
	}
			
	$someFile     = $_FILES['fileUpload']['tmp_name'];
	$someFileName = $_FILES['fileUpload']['name'];
	$someFileType = $_FILES['fileUpload']['type'];
	$someFileSize = $_FILES['fileUpload']['size'];
	
	if ( ($formAction == 'add') && empty($someFile) ) {
		$error = 1;
		$message = 'You must select a file to upload.';
	}	
		
	// Clean Filename
	$filename = cleanString($someFileName);		
	$fileDir  = PUBLIC_FILES_PATH.'resource_files/';	
		
	if ($error != 1) {
		if (!empty($newCatField) || !empty($newSubCatField)) {
			/*
			 * Enter new category
			 */
			 if ($ptiSharedResource == 1) {
			 	$siteArea = 'Shared Resource File';
			 } else {
			 	$siteArea = 'Resource File';
			 }
			 
			 if (!empty($newCatField)) {
			 	$catType = 'main';
			 	$catName = $newCatField;
			 } elseif (!empty($newSubCatField)) {
			 	$catType = 'sub';
			 	$catName = $newSubCatField;
			 	
			 	/*
			 	 * Get main category name
			 	 */
				$sql = "SELECT DirectoryName 
						FROM cdc_sysCategory 
						WHERE CatID = '$fileCat'";
				$result = mysql_db_query($dbname,$sql);
				$row = mysql_fetch_assoc($result);
				$mainDirName = $row['DirectoryName'];
				$fileDir .= $mainDirName.'/';				
			 }
			 
			 $catArray = array(
			 					'CatName'   => $catName,
			 					'CatType'   => $catType,
			 					'SiteArea'  => $siteArea,
			 					'ParentID'  => $fileCat,
			 					'CreateDir' => '1',
			 					'ParentDir' => $fileDir
			 					);
			 
			 $newCatArray = createNewCategory($catArray);
			 $filePath = $newCatArray['CatDir'].'/'.$filename;
			 $fileCat  = $newCatArray['CatID'];			 
		} else {
			/*
			 * Get directory name from category table
			 */
			$sql = "SELECT DirectoryName 
					FROM cdc_sysCategory 
					WHERE CatID = '$fileCat'";
			$result = mysql_db_query($dbname,$sql);
			$row = mysql_fetch_assoc($result);
			$dirName = $row['DirectoryName'];
			
			if (!empty($fileSubCat) && ($fileSubCat != 'Select...') ) {
				$sql = "SELECT DirectoryName 
					FROM cdc_sysCategory 
					WHERE CatID = '$fileSubCat'";
				$result = mysql_db_query($dbname,$sql);
				$row = mysql_fetch_assoc($result);
				$fileCat = $fileSubCat;
				$dirName .= '/'.$row['DirectoryName'];
			}			
			
			$filePath = $fileDir.$dirName.'/'.$filename;
		}				
		
		// Add file to database
		if ($_SESSION['userLevel'] == 1) {
			$approved = 1;
		} else {
			$approved = 0;
		}
		$approved = 1;
			
		if ($formAction == 'add') {
			move_uploaded_file($someFile, $filePath);
			$sql = "INSERT into cdc_Files (
					CatID,
					FileTitle,
					FileDesc,
					FileName,
					FileSize,
					FileType,
					Approved,
					DateUpdate,
					Userid
					) values (
					'$fileCat',
					'$fileTitle',
					'$fileDesc',
					'$filename',
					'$someFileSize',
					'$someFileType',					
					'$approved',
					'".date('Y-m-d')."',
					'".$_SESSION['userid']."'					
					)";
		} elseif ($formAction == 'edit') {
			if (!empty($someFile)) {
				/*
				 * Delete original file
				 */
				$origFilePath = $_POST['origFilePath'];
				unlink($origFilePath);
				move_uploaded_file($someFile, $filePath);
			}
			$sql = "UPDATE cdc_Files SET
					CatID      = '$fileCat',
					FileTitle  = '$fileTitle',
					FileDesc   = '$fileDesc',
					FileName   = '$filename',
					FileSize   = '$someFileSize',
					FileType   = '$someFileType',
					Approved   = '$approved',
					DateUpdate = '".date('Y-m-d')."',
					Userid     = '".$_SESSION['userid']."'
					WHERE
					FID = '$fID'";
		}
		$result = mysql_db_query($dbname,$sql);	
	}	
} else {
	$error = 0;
	$upload = 0;	
}
/*
 * To here...cut and make separate file processing script so AIR app can use it too
 */

if (!empty($_GET['fID'])) {
	/*
	 * Get file information for edit
	 */
	$fileArray = getResourceFile($_GET['fID'],'array');
	
	$fID       = $fileArray['FID'];
	$fileCat   = $fileArray['MainCatID'];
	$fileSubCat= $fileArray['SubCatID'];
	$fileTitle = $fileArray['FileTitle'];
	$fileDesc  = $fileArray['FileDesc'];
	$fileName  = $fileArray['FileName'];
	$fileURL   = $fileArray['FileURL'];
	$filePath  = $fileArray['FilePath'];
	$siteArea  = $fileArray['SiteArea'];
	$formAction= 'edit';
}
?>

<html><head>
	<link rel="stylesheet" type="text/css" href="css/browserReset.css?r=<? echo random_string(5,'numeric'); ?>">
	<link rel="STYLESHEET" media="screen" href="css/stylesMozilla.css?r=<? echo random_string(5,'numeric'); ?>" type="text/css" />	
	
	<!-- WYSIWYG Editor stuff -->
	<script src="js/tinyeditor/tiny_mce.js" language="javascript" type="text/javascript"></script>					
	<script src="js/tinyeditor/config/mceConfig.js" language="javascript" type="text/javascript"></script>
	<!-- End WYSIWYG Editor stuff -->		
	
	<script src="js/protaculous/prototype1.6.js" language="JavaScript" type="text/javascript"></script>
	<script src="js/protaculous/scriptaculous.js?load=effects,dragdrop,combo,controls" language="JavaScript" type="text/javascript"></script>
</head>
<body onload="jScriptInit(); uploadComplete(<?=$upload; ?>,<?=$error; ?>);">
<div>
	<div id="statusDiv" class="errorMessageBig" style="display: <?=$statusDivDisplay; ?>"><?=$message; ?></div>
	<form name="iform" action="<?=$_SERVER['PHP_SELF']; ?>" id="iform" method="post" enctype="multipart/form-data">
	<input type="hidden" name="upload" value="1">
	<input type="hidden" id="tempMainCat" value="<?=$fileCat; ?>">
	<input type="hidden" id="tempSubCat" value="<?=$fileSubCat; ?>">
	<input type="hidden" id="origFilePath" name="origFilePath" value="<?=$filePath; ?>">
	
	<input type="hidden" name="formAction" id="formAction" value="<?=$formAction; ?>" />
			<input type="hidden" name="fID" id="fID" value="<?=$fID; ?>" />				
			<p>
				<input type="checkbox" name="ptiSharedResource" id="ptiSharedResource" value="1" 
				<? if ($siteArea == 'Shared Resource File') { ?>
					checked
				<? } ?>	
				onClick="window.parent.resourcesSupportObj.getSharedResourceCats();" /> <b>This is a PTI Shared Resource</b>
			</p>
					
			<p><span class="vertLabelSmall">Category &nbsp;&nbsp;<a href="#" id="newCatLinkMain" onClick="window.parent.resourcesSupportObj.newCategoryForm('main'); return false;">New Category</a></span>
				<select id="fileCat" name="fileCat" size="1" onChange="window.parent.resourcesSupportObj.getFileCategories(null,'json','sub',this.options[selectedIndex].value);" style="width: 400px;">
				<option>Select...</option>
				</select>
				<input type="text" style="width: 400px; display: none;" name="newCatFieldMain" id="newCatFieldMain" />
			</p>
			
			<p style="display: none;" id="subCatContainer"><span class="vertLabelSmall">Sub Category &nbsp;&nbsp;<a href="#" id="newCatLinkSub" onClick="window.parent.resourcesSupportObj.newCategoryForm('sub'); return false;">New Category</a></span>
				<select id="fileSubCat" name="fileSubCat" size="1" style="width: 400px;">
				<option>Select...</option>
				</select>
				<input type="text" style="width: 400px; display: none;" name="newCatFieldSub" id="newCatFieldSub" />
			</p>
			
			<p><span class="vertLabelSmall">Title</span>
			<input type="text" style="width: 400px;" id="fileTitle" name="fileTitle" value="<?=$fileTitle; ?>" /></p>
			
			<p><span class="vertLabelSmall">Short description</span>
			<textarea name="fileDesc" class="editorSimple" id="fileDesc" style="width: 500px; height: 150px;"><?=$fileDesc; ?></textarea>
			</p>			

			<p><span class="vertLabelSmall">
				<? if (!empty($filePath)) {	?>
				Existing File: <a href="<?=$fileURL; ?>" target="_blank"><?=$fileName; ?></a><br />
				<? } else { ?>
				Select File
				<? } ?>
				</span>
				<input type="file" id="fileUpload" name="fileUpload" size="50" />
			</p>		
			
			<div style="margin-top: 10px; margin-left: 5px;">
				<div style="float: left; margin-right: 5px;">
					<a href="#" class="coolButton buttonBGBlueGray" tabindex="30" onClick="uploadFile();"><span class="save">Save</span></a>
				</div>
				<div style="float: left;">
					<a href="#" class="coolButton buttonBGRed" tabindex="30" onClick="window.parent.resourcesSupportObj.closeAddEditForm(); return false;"><span class="cancel">Cancel</span></a>
				</div>
				<div style="clear: left;"></div>
			</div>				
	</form>
</div>	
<SCRIPT src="js/jsCommon.js" language="JavaScript" type="text/javascript"></SCRIPT>
	
<script language="JavaScript" type="text/javascript">
	var par = window.parent;
	
	function uploadComplete(upload,error) {
		if (upload == 1) {
			var progressDiv = par.$('progressDiv');
			if (error == 1) {
				progressDiv.className = 'errorMessageBig';
				progressDiv.innerHTML = '<?=$message; ?>';
			} else {
				// Refresh file list
				//window.parent.filesViewObj.refreshFileList(<?=$fileCat; ?>,<?=$fileSubCat; ?>);
				progressDiv.className = 'successMessageBig';
				progressDiv.innerHTML = '<b>Your Upload Was Successful!</b>';					
			}
		}
	}
	function uploadFile(){	
		var progressDiv = par.$('progressDiv');
		var form   = $('iform');	
		progressDiv.className = 'activityMessageBig';	
		progressDiv.innerHTML = '<b>Your file is uploading...</b>';
				
		//progressDiv.innerHTML = '<img src="images/ajaxAnimBar.gif"> <b>Your file is uploading...</b>';
			
		/*
		 * Upload the file
		 */
		form.submit();	
	}
	
	function getSubCategories(catID) {
		var params = 'handler=getSubCategories&display=json&siteArea=F&catID='+catID;
		
		var ajaxResults = new Ajax.Request('functions.php', {
			method: 'POST',
			parameters: params,	
			onSuccess: function(transport) {
				returnGetSubCategories(transport.responseText);
			},
			onFailure: function() {
				alert('Oops!');
			}		
		});
	}

	function returnGetSubCategories(ajaxResult) {
		if (ajaxResult != '0') {
			var jsonObject = eval('(' + ajaxResult + ')');
			var totalCategories = (jsonObject.categories.length)-1;
			for(i=0;i<=totalCategories;i++) {
				var catID   = jsonObject.categories[i].CID;
				var catName = jsonObject.categories[i].CatName;
				$('subCatSelect').options[i] = new Option(catName,catID);
			}
			$('subCatContainer').style.display = '';
		} else {
			$('subCatContainer').style.display = 'none';
		}
	}
	function jScriptInit(formAction) {
		window.parent.resourcesSupportObj.getSharedResourceCats();		
		if ($('tempSubCat').value>0) {
			window.parent.resourcesSupportObj.getFileCategories(null,'json','sub',$('tempMainCat').value);
		}
	}
</script>
</body>	
</html>